#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define PORT 1234
#define MAXDATASIZE 100

int main(int argc, char** argv){
    int sockfd;
    int num;
    char buf[MAXDATASIZE];
    struct hostent* he;
    struct sockaddr_in server, peer;//分别是发送的目的地址,从服务器返回的地址

    // 通过命令行将参数传递,分别是目的IP地址和消息
    if(argc != 3){
        printf("Usage: %s <IP ADRESS> <MESSAGE>\n", argv[0]);
        exit(1);
    }

    if((he = gethostbyname(argv[1])) == NULL){
        printf("gethostbyname error\n");
        exit(1);
    }

    if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1){
        printf("socket error\n");
        exit(1);
    }

    // 将通过命令行传入的IP地址填充到地址结构中
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(PORT);
    server.sin_addr = *((struct in_addr*) he->h_addr);

    // 将消息传送给目的IP地址
    sendto(sockfd, argv[2], strlen(argv[2]), 0, (struct sockaddr*) &server, sizeof(server));

    socklen_t len = sizeof(server);

    while(1){
        // 接收从服务端发送的数据,填充到buf缓冲区当中
        if((num = recvfrom(sockfd, buf, MAXDATASIZE, 0, (struct sockaddr*) &peer, &len)) == -1){
            printf("recvfrom error");
            exit(1);
        }

        if(len != sizeof(server) || memcmp((const void*) &server, (const void*) &peer, len) != 0){
            printf("Receive message from other server.\n");
            continue;
        }
        buf[num] = '\0';
        printf("Server Message: %s.\n", buf);
        break;
    }

    close(sockfd);

    return 0;

}